package com.dx.financehy.utils;


import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.dx.financehy.domain.vo.CheckResultVO;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.*;

/**
 * @Author: linjiang
 * @Description:
 * @Date: Created in 17:21 2021/11/02
 * @Modified By:
 */
@Slf4j
public class NucleicResultUtils {


    /**
     * 预警系统加密
     *
     * @param jsonObject
     * @return
     */
    public static String encryption(JSONObject jsonObject) {
        try {
            JSONObject allObject = new JSONObject();
            String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCnUiXAQud+1PsNYkBYQlDA8XHN1MtvyMHyhyg87eQM4VS/831uXPNDx0U4iloOFwjGKwNlUIAy1PO4ReYtyCEj2N0jCR1ZtK1E9FgR7DKyWRFAcdbgD0XUqTstedq1eHTmuxpnK/brY2kTSI1ZsFqb8gbRbJrfOw5g3vuubc1q/wIDAQAB";
            String privateKey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKdSJcBC537U+w1iQFhCUMDxcc3Uy2/IwfKHKDzt5AzhVL/zfW5c80PHRTiKWg4XCMYrA2VQgDLU87hF5i3IISPY3SMJHVm0rUT0WBHsMrJZEUBx1uAPRdSpOy152rV4dOa7Gmcr9utjaRNIjVmwWpvyBtFsmt87DmDe+65tzWr/AgMBAAECgYBl4WYtME/G8aZAGwA0/YQwR5PVEeohkatOoq+EkhGXKikxi/BnH9/b+F0UtWFqTOpBx/UUXrUAvpv8K0uhusc6D7mxvuRkX6hdo3WD00FkNRS8kPgFbL2igHa1h1WB17T3GVDzGc93xUvkNOlnA/BWIX1wqEonXyCKzhSJAq+3EQJBAOlZdsc8pQJQLpTRXQyYFeRPENm4WZsNLfxrihzwHr43Qfm5A0qboYVLfpBylqa6fFKKG/Sp/b5BH8ufBLd5+ZkCQQC3j+3rgIvRixh3NC9+6YC1CHyAgECc4xiOxGYQqiWHf1zM4FAcLj/2ymxk7VYHGHq1J3ZWgYVZnwUgrymMFVhXAkEAxtRmMwnnh/sOVdu3L13/eVQthXZhU459WpG/Uzz+1RF8c+5DcbT+gfd71lTtLQ/Fkwb/HxAhl5UiJHxQpo2WMQJAbYsBCtdtmSEO+qQz6+LhIifsVKs04+tKTni6CBvhxZimAsWiSQ74sQhf42MXQajEIbNpFXq535/caYLeonBihQJBAKUE3DznaJp7yKz+/A/FrjMe6Cu7ioRZW7UBvAKLIp6Y2VAUEFzczYNtUxi34suxjnznvJw0MgIhCixmfw3BwQE=";
            //公钥加密
            String enStr1 = DecryptUtils.encryptByPublicKey(jsonObject.toString(), publicKey);
            //私钥签名
            String sign = DecryptUtils.sign(enStr1, privateKey);
            allObject.put("data", enStr1);
            allObject.put("sysName", "warming_system");
            allObject.put("passwd", "49b8e85effb088cb34172396af6d3e6e");
            allObject.put("serviceName", "warming_system_nat_data");
            allObject.put("sign", sign);
            return allObject.toString();
        } catch (Exception e) {
            log.error("encrypt----加密方法异常" + e);
            return "";
        }
    }

    /**
     * 数据加密
     *
     * @param jsonStr
     * @return
     */
    public static String encryptionString(String jsonStr) {
        String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCnUiXAQud+1PsNYkBYQlDA8XHN1MtvyMHyhyg87eQM4VS/831uXPNDx0U4iloOFwjGKwNlUIAy1PO4ReYtyCEj2N0jCR1ZtK1E9FgR7DKyWRFAcdbgD0XUqTstedq1eHTmuxpnK/brY2kTSI1ZsFqb8gbRbJrfOw5g3vuubc1q/wIDAQAB";
        String enStr1 = DecryptUtils.encryptByPublicKey(jsonStr, publicKey);
        return enStr1;
    }

    /**
     * 数据解密
     *
     * @param jsonStr
     * @return
     */
    public static String decryption(String jsonStr) {
        String privateKey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKdSJcBC537U+w1iQFhCUMDxcc3Uy2/IwfKHKDzt5AzhVL/zfW5c80PHRTiKWg4XCMYrA2VQgDLU87hF5i3IISPY3SMJHVm0rUT0WBHsMrJZEUBx1uAPRdSpOy152rV4dOa7Gmcr9utjaRNIjVmwWpvyBtFsmt87DmDe+65tzWr/AgMBAAECgYBl4WYtME/G8aZAGwA0/YQwR5PVEeohkatOoq+EkhGXKikxi/BnH9/b+F0UtWFqTOpBx/UUXrUAvpv8K0uhusc6D7mxvuRkX6hdo3WD00FkNRS8kPgFbL2igHa1h1WB17T3GVDzGc93xUvkNOlnA/BWIX1wqEonXyCKzhSJAq+3EQJBAOlZdsc8pQJQLpTRXQyYFeRPENm4WZsNLfxrihzwHr43Qfm5A0qboYVLfpBylqa6fFKKG/Sp/b5BH8ufBLd5+ZkCQQC3j+3rgIvRixh3NC9+6YC1CHyAgECc4xiOxGYQqiWHf1zM4FAcLj/2ymxk7VYHGHq1J3ZWgYVZnwUgrymMFVhXAkEAxtRmMwnnh/sOVdu3L13/eVQthXZhU459WpG/Uzz+1RF8c+5DcbT+gfd71lTtLQ/Fkwb/HxAhl5UiJHxQpo2WMQJAbYsBCtdtmSEO+qQz6+LhIifsVKs04+tKTni6CBvhxZimAsWiSQ74sQhf42MXQajEIbNpFXq535/caYLeonBihQJBAKUE3DznaJp7yKz+/A/FrjMe6Cu7ioRZW7UBvAKLIp6Y2VAUEFzczYNtUxi34suxjnznvJw0MgIhCixmfw3BwQE=";
        String deStr = DecryptUtils.decryptByPrivateKey(jsonStr, privateKey);
        return deStr;
    }

    /**
     * 预警系统解密
     *
     * @param jsonStr
     * @return
     */
    public static void DecryptionRM(String jsonStr) {

        String publicKey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCnUiXAQud+1PsNYkBYQlDA8XHN1MtvyMHyhyg87eQM4VS/831uXPNDx0U4iloOFwjGKwNlUIAy1PO4ReYtyCEj2N0jCR1ZtK1E9FgR7DKyWRFAcdbgD0XUqTstedq1eHTmuxpnK/brY2kTSI1ZsFqb8gbRbJrfOw5g3vuubc1q/wIDAQAB";
        String privateKey = "MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKdSJcBC537U+w1iQFhCUMDxcc3Uy2/IwfKHKDzt5AzhVL/zfW5c80PHRTiKWg4XCMYrA2VQgDLU87hF5i3IISPY3SMJHVm0rUT0WBHsMrJZEUBx1uAPRdSpOy152rV4dOa7Gmcr9utjaRNIjVmwWpvyBtFsmt87DmDe+65tzWr/AgMBAAECgYBl4WYtME/G8aZAGwA0/YQwR5PVEeohkatOoq+EkhGXKikxi/BnH9/b+F0UtWFqTOpBx/UUXrUAvpv8K0uhusc6D7mxvuRkX6hdo3WD00FkNRS8kPgFbL2igHa1h1WB17T3GVDzGc93xUvkNOlnA/BWIX1wqEonXyCKzhSJAq+3EQJBAOlZdsc8pQJQLpTRXQyYFeRPENm4WZsNLfxrihzwHr43Qfm5A0qboYVLfpBylqa6fFKKG/Sp/b5BH8ufBLd5+ZkCQQC3j+3rgIvRixh3NC9+6YC1CHyAgECc4xiOxGYQqiWHf1zM4FAcLj/2ymxk7VYHGHq1J3ZWgYVZnwUgrymMFVhXAkEAxtRmMwnnh/sOVdu3L13/eVQthXZhU459WpG/Uzz+1RF8c+5DcbT+gfd71lTtLQ/Fkwb/HxAhl5UiJHxQpo2WMQJAbYsBCtdtmSEO+qQz6+LhIifsVKs04+tKTni6CBvhxZimAsWiSQ74sQhf42MXQajEIbNpFXq535/caYLeonBihQJBAKUE3DznaJp7yKz+/A/FrjMe6Cu7ioRZW7UBvAKLIp6Y2VAUEFzczYNtUxi34suxjnznvJw0MgIhCixmfw3BwQE=";
        String password = "49b8e85effb088cb34172396af6d3e6e";
        String resultStr = "";
        try {

            JSONObject jsonObject = JSONObject.parseObject(jsonStr);
            //data：公钥加密串
            String data = jsonObject.getString("data");
            String sysName = jsonObject.getString("sysName");
            String sysPasswd = jsonObject.getString("passwd");
            String sign = jsonObject.getString("sign");
            String serviceName = jsonObject.getString("serviceName");
            //根据Id去数据库查询出医院的rsa信息，然后拿私钥进行解密
            if (sysPasswd.equals(password)) {
                resultStr = new String(DecryptUtils.decryptByPrivateKey(data, privateKey));
                if (!DecryptUtils.verify(data, publicKey, sign)) {
                    //R.fail(CodeDefault.REQ_SIGN_ID_ERROR, null);
                    log.error("请求签名ID错误");
                }
            } else {
                log.error("用户名密码错误");
                //R.fail(CodeDefault.REQ_USERNAME_PASSWD_ERROR, null);
            }
        } catch (Exception e) {
            log.error("RSAController.reqService: ,jsonStr: {},exception:{}", jsonStr, e);
            Map<String, Object> errorMap = new HashMap<>();
            errorMap.put("msg", e.getMessage());
            //return R.fail(CodeDefault.ILLEGAL_ARGUMENT, errorMap);
            log.error("非法论据");
        }
    }


    public static String postFeverPersion(String jsonStr, String url) {
        //测试地址
//        String ip ="http://localhost:9999";
        //正式地址
//         String ip = "http://10.111.174.243:9000/";
//        本地测试环境
        //String ip = "http://10.111.174.243:9000/";
        String ip = "http://10.111.175.20:50018/";
        //最新测试环境
        ip = "http://10.111.175.65:50025/";
        String result = "";
        //加密服务器地址
        log.info("(核酸信息关联)请求的接口地址=====>" + ip + url);
        HttpPost post = new HttpPost(ip + url);
        RequestConfig requestConfig = RequestConfig.custom()
                .setConnectTimeout(3000)
                .setConnectionRequestTimeout(3000)
                .setSocketTimeout(3000).build();
        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpEntity httpEntity = null;
        try {

            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("jsonStr", jsonStr));
            httpEntity = new UrlEncodedFormEntity(params, "UTF-8");
            post.setConfig(requestConfig);
            post.setEntity(httpEntity);
            HttpResponse response = httpClient.execute(post);
            InputStream in = response.getEntity().getContent();
            BufferedReader br = new BufferedReader(new InputStreamReader(in, "utf-8"));
            StringBuilder strber = new StringBuilder();
            String line = null;
            while ((line = br.readLine()) != null) {
                strber.append(line + '\n');
            }
            br.close();
            in.close();
            result = strber.toString();
            if (response.getStatusLine().getStatusCode() != HttpStatus.SC_OK) {
                result = "";
            }
        } catch (Exception e) {
            log.error("api-postHttp--请求http异常" + e);
            result = "";
        } finally {
            //统一关闭
            try {
                post.releaseConnection();
                httpClient.close();
                EntityUtils.consume(httpEntity);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return result;
    }

    public static void main(String[] args) throws Exception {


        JSONObject requestData = new JSONObject();

        List<String> list = new LinkedList<>();
        list.add("M34551419");
        list.add("23010719920801246X");
        list.add("469007199708217619");
        list.add("460021197310013616");
        requestData.put("list", list);

        System.out.println(requestData.toJSONString());
        //对返回的参数数据解密
        String request = postFeverPersion(NucleicResultUtils.encryption(requestData), "/checkResult/Info/getCheckResultListToLD");
        /*JSONObject data = JSONObject.parseObject(request);
        //对返回的参数数据解密
        String   returnData  = Test2.decryption(data.get("data").toString());*/

        System.out.println(request);
    }

    /**
     * 通过身份证、姓名、手机号获取用户核酸信息
     *
     * @param idCard
     * @return
     */
    public static List<CheckResultVO> getNATResult(String idCard, String phoneNum, String userName) {
        JSONObject requestData = new JSONObject();
        requestData.put("cardId", idCard);
        requestData.put("phoneNum", phoneNum);
        requestData.put("userName", userName);
        log.info("(核酸信息关联)要查询核酸信息的身份证号=====>" + requestData.toJSONString());
        //请求加密
        String request = postFeverPersion(NucleicResultUtils.encryption(requestData), "checkResult/Info/getCheckResultListToLDV2");
        try {
            if (!StringUtils.isBlank(request)){
                JSONObject data = JsonUtils.toObject(request);
                log.info("(核酸信息关联)返回的核酸检测记录信息,加密前=====>" + data);
                //对返回的参数数据解密
                if (data != null) {
                    String returnData = NucleicResultUtils.decryption(data.get("data").toString());
                    log.info("(核酸信息关联)返回的核酸检测记录信息,解密后=====>" + returnData);
                    return JSONArray.parseArray(returnData, CheckResultVO.class);
                }
            }
        } catch (Exception e) {
            log.error("(核酸信息关联)获取核酸检测结果异常====>" + e);
        }
        return new ArrayList<>();
    }


}
